<?php
/**[内容视图模型]
 * @Author: 976123967@qq.com
 * @Date:   2014-08-15 18:14:52
 * @Last Modified by:   Administrator
 * @Last Modified time: 2014-12-15 14:30:51
 */

class ArticleViewModel extends ViewModel{
	protected $tableName='article';

	public $viewFields  = array(
		'article'=>array(
			'*',
			'_type'=>'INNER',
		),
		'user'=>array(
			'username','uid',
			'_type'=>'INNER',
			'_on' =>'user.uid=article.user_uid',
		),
		'category'=>array(
			'cid','cname','remark',
			'_type'=>'INNER',
			'_on' =>'category.cid=article.category_cid',
		)
	);
	/**
	 * [get_data 内容列表]
	 * @param  integer $admin [description]
	 * @return [type]         [description]
	 */
	public function get_data($admin=1,$order='',$field=null)
	{


		$cid = I('get.cid',null,'intval');

		// 关联表
		$mid = D('Category')->get_field($cid,'model_mid');
		$table = 'article_'.D('Model')->get_field($mid,'name');
		$extField = D('Field')->get_lists_field($mid);

		$this->viewFields[$table] = array(
			'*',
			'_type'=>'INNER',
			'_on'=>$table.'.article_aid=article.aid'

		);



		$where = null;
		if(isset($uid))
		{
			$where['user_uid'] = $uid;
		}
		// 前台只显示审核通过的
		if(!$admin)
		{
			$where['verifystate'] = 2;
		}
		// 审核状态
		switch (I('get.sta',null,'intval')) 
		{
			case 1:
				$verifystate =1;
				break;
			case 2:
				$verifystate =2;
				break;
			default:
				$_GET['sta']=2;
				$verifystate =2;
				break;
		}
		if(isset($verifystate))
		{
			$where['verifystate'] = $verifystate;

		}
		// 关键字查找
		$keyword = I('get.search_keyword');


		if($keyword)
		{
			// 类型
			switch (I('get.search_type',null,'intval')) 
			{
				case 1:	//标题
					$where[] = 'article_title like "%'.$keyword.'%"';
					break;
				case 2: //简介
					$where[] ='description like "%'.$keyword.'%"';
					break;
				case 3: //用户名
					$uid = D('User')->where('username like "%'.$keyword.'%"')->getField('uid');
					$where['user_uid'] = $uid;
					break;
				case 4: //用户名id
					$where['user_uid'] = $keyword;
					break;
				default:
					$where[] = ' article_title like "%'.$keyword.'%" ';
			}
		}

		// 分类
		
		$categoryModel = D('Category');
		if($cid)
		{
			// 获取所有的子cid
			$childCid = $categoryModel->get_child_cid($cid);
			$where['category_cid'] = array('in',$childCid) ;
		}

		// 属性
		$flag = I('get.flag');
		if($flag)
		{
		
			$where[] = "find_in_set('{$flag}',flag)";
		}

		// 时间
		$starttime = I('get.search_begin_time');

		if($starttime)
		{
			$where[] ='addtime >='.strtotime($starttime);
		}

		$endtime = I('get.search_end_time');
		if($endtime)
		{
			//需要修正时间应该是到这一天的结束，所以要加上一天的时间
			$where[] ='addtime <='.(strtotime($endtime)+24*3600);
		}
		

		// 每页记录数
		$pageCount = 20;
		// 每页记录数 后台固定20条一页 ，前台读取分类中的信息，前台必须传递get.cid
		$pageCount = $admin ? $pageCount : $categoryModel->get_field($cid,'page');
		// 排序
		if(!$order)
			$order = 'article.sort asc ,aid desc';
		// 总数
		$count = $this->where($where)->count();


		import('ORG.Util.Page');// 导入分页类
		// import('Class.Page',APP_PATH);
		$page = new Page($count,$pageCount);
		if(is_null($field))
			$field='sort,verifystate,aid,category_cid,article_title,keywords,description,username,cname,remark,edittime,addtime,pic,content,file,flag';
		if($extField)
			$field .= ','.$extField;

		//p($this->viewFields);die;
		$data = $this->field($field)->where($where)->order($order)->limit($page->firstRow.','.$page->listRows)->select();
		// echo $this->_sql();die;
		// p($data);die;

		if(!$data) return $data;
		foreach($data as $k=>$v)
		{
			switch ($v['verifystate']) 
			{
				case 1:
					$data[$k]['verifystate']='审核中';
					break;
				
				case 2:
					$data[$k]['verifystate']='通过';
					break;
			}
			// 编辑时间
			$data[$k]['edittime'] = date('Y-m-d',$v['edittime']);
			// 发布时间
			$data[$k]['time'] = $v['addtime'];
			$data[$k]['addtime'] = date('Y-m-d',$v['addtime']);
			// 图片
			$data[$k]['pic']= $v['pic']?__ROOT__.'/'.$v['pic']:__ROOT__.'/Data/Image/default.gif';

			// 文件下载
			if(is_file($v['file']))
			{
				$data[$k]['size'] = get_size(filesize($v['file']));
			}
			$data[$k]['file']= $v['file']?__ROOT__.'/'.$v['file']:'';
			$data[$k]['downurl'] = U('down',array('aid'=>$v['aid'],'cid'=>$v['category_cid']));

			// 当前栏目URL地址
			$cateInfo = $categoryModel->find_one($v['category_cid']);
			$data[$k]['cat_url'] = $categoryModel->get_url($cateInfo);

		}

		$page->setConfig('theme','<span>%totalRow% %header% %nowPage%/%totalPage% 页 </span>%upPage% %downPage% %first% %prePage% %linkPage% %nextPage% %end%');

		// 设置翻页语言
		if(isset($_SESSION['curTheme'])&& $_SESSION['curTheme'] == "en")
		{
			$page->setConfig('header',' record ');
			$page->setConfig('prev',' prev ');
			$page->setConfig('next',' next ');
			$page->setConfig('first',' first ');
			$page->setConfig('last',' last ');
			$page->setConfig('theme','<span>%totalRow% %header% %nowPage%/%totalPage% page </span>%upPage% %downPage% %first% %prePage% %linkPage% %nextPage% %end%');
		}

		$data['page'] = $page->show();

	 //p($data);die;

		return $data;

	}

	


	/**
	 * [get_article_one 获取单条信息]
	 * @param  [type] $aid [description]
	 * @return [type]      [description]
	 */
	public function  get_article_one($aid)
	{
		// 关联表
		$cid = D('Article')->get_field($aid,'category_cid');
		$mid = D('Category')->get_field($cid,'model_mid');
		$table = 'article_'.D('Model')->get_field($mid,'name');
	

		$this->viewFields[$table] = array(
			'*',
			'_type'=>'INNER',
			'_on'=>$table.'.article_aid=article.aid'

		);


		// 执行模型中的find
		$data=$this->where(array('aid'=>$aid))->find();

		
		if($data['pic'])
		{
			$data['has_pic'] = true;
		}
		if($data['file'])
		{
			$data['has_file'] = true;
		}

		$data['pic']= $data['pic']?__ROOT__.'/'.$data['pic']:__ROOT__.'/Data/Image/default.gif';

		if(is_file($data['file']))
		{
			$data['size'] = get_size(filesize($data['file']));
		}
		$data['downurl'] = U('down',array('aid'=>$data['aid'],'cid'=>$data['category_cid']));


		return $data;
	}

	/**
	 * [get_field 获取指定值]
	 * @param  [type] $aid   [description]
	 * @param  [type] $field [description]
	 * @return [type]        [description]
	 */
	public function get_field($aid,$field)
	{
		// 关联表
		$cid = D('Article')->get_field($aid,'category_cid');
		$mid = D('Category')->get_field($cid,'model_mid');
		$table = 'article_'.D('Model')->get_field($mid,'name');
	

		$this->viewFields[$table] = array(
			'*',
			'_type'=>'INNER',
			'_on'=>$table.'.article_aid=article.aid'

		);


		// 执行模型中的getField
		return $this->where(array('aid'=>$aid))->getField($field);

	}



	/**
	 * [get_filter_lists  获取筛选后信息]
	 * @return [type] [description]
	 */
	public function get_filter_lists()
	{

		$cid = I('get.cid',null,'intval');


		// 基本where
		$where = ' where 1 ';
		// 分类
		$categoryModel = D('Category');
		if($cid)
		{
			// 获取所有的子cid
			$childCid = $categoryModel->get_child_cid($cid);
			$where .= " AND article.category_cid in (". implode(',', $childCid).")";
		}
		// 审核通过
		$where .= " AND  article.verifystate  = 2 ";

		// 关键字查找
		$keyword = I('get.search_keyword');
		if($keyword)
			$where .= ' AND (article.article_title_en like "%'.$keyword.'%"   or article.article_title like "%'.$keyword.'%" ) ';



		// 筛选
		$s = I('get.s');
		$sArr = explode('-', $s);
		// 过滤0
		$filter  = array();
		foreach ($sArr as $v) 
		{
			if($v)
				$filter[] = $v;
		}
		$from = " FROM ".C('DB_PREFIX')."article AS article JOIN  ".C('DB_PREFIX')."category AS category ";
		$join = " JOIN ";
		foreach($filter as $k=> $v)
		{
			$join .= C('DB_PREFIX').'article_attr as a'.$k ." JOIN ";
		}
		$join = rtrim($join,'JOIN ');
		//echo $join;

		$on=" ON article.category_cid = category.cid AND  ";
		foreach($filter as $k=> $v)
		{
			$on.=" a{$k}.article_aid=article.aid AND ";
		}
		$on = rtrim($on,'AND ');

		//where
		foreach($filter as $k=> $v)
		{
			$where.=" AND a{$k}.attr_value_attr_value_id = $v ";
		}

		$order = ' order by article.sort asc, article.aid desc, article.addtime desc ';



		$sql = ' SELECT count(*) as count '.$from.$join.$on.$where;
		$countArr = $this->query($sql);

		// 总数
		$count = $countArr[0]['count'];

		import('ORG.Util.Page');// 导入分页类
		// import('Class.Page',APP_PATH);
		$page = new Page($count,28);

		// limit
		$limit = " LIMIT ".$page->firstRow.','.$page->listRows;
		// 组合sql
		$sql = " SELECT article.*,category.remark  ".$from.$join.$on.$where.$order.$limit;
		//echo($sql);
		$data = $this->query($sql);	
		if(!$data) return $data;
		foreach($data as $k=>$v)
		{
			
			// 编辑时间
			$data[$k]['edittime']=date('Y-m-d',$v['edittime']);
			// 发布时间
			$data[$k]['addtime']=date('Y-m-d',$v['addtime']);
			// 图片
			$data[$k]['pic']= $v['pic']?__ROOT__.'/'.$v['pic']:__ROOT__.'/Data/Image/default.gif';

			// 文件下载
			if(is_file($v['file']))
			{
				$data[$k]['size'] = get_size(filesize($v['file']));
			}
			$data[$k]['file']= $v['file']?__ROOT__.'/'.$v['file']:'';
			$data[$k]['downurl'] = U('down',array('aid'=>$v['aid'],'cid'=>$v['category_cid']));

			$data[$k]['url'] = U('/products/v_'.$v['category_cid'].'_'.$v['aid']);

		}

		$page->setConfig('theme','<span>%totalRow% %header% %nowPage%/%totalPage% 页 </span>%upPage% %downPage% %first% %prePage% %linkPage% %nextPage% %end%');
		// 设置翻页语言
		if(isset($_SESSION['curTheme'])&& $_SESSION['curTheme'] == "en")
		{
			$page->setConfig('header',' record ');
			$page->setConfig('prev',' prev ');
			$page->setConfig('next',' next ');
			$page->setConfig('first',' first ');
			$page->setConfig('last',' last ');
			$page->setConfig('theme','<span>%totalRow% %header% %nowPage%/%totalPage% page </span>%upPage% %downPage% %first% %prePage% %linkPage% %nextPage% %end%');
		}


		$data['page'] = $page->show();
		
	
		return $data;

	}






}